package com.suyafei.es.configuration;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @program: es-homework
 * @description
 * @author: luffy
 * @create: 2020-12-10 13:53
 */

@Configuration
public class ElasticsearchConfig{


    //myelaticsearch.elasticsearch.hostlist
    @Value("${myelaticsearch.elasticsearch.hostlist}")
    private String hostlist;


    @Bean
    public RestHighLevelClient esClient() {
        String[] split = hostlist.split(",");
        HttpHost[] httpHosts = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String item = split[i];

            httpHosts[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");

        }
        return new RestHighLevelClient(RestClient.builder(httpHosts));
    }

    @Bean
    public RestClient restClient(){
        String[] split = hostlist.split(",");
        HttpHost[] httpHosts = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String item = split[i];

            httpHosts[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");

        }
        return RestClient.builder(httpHosts).build();
    }
}
